Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Parallelism CPU calculation inside Kubernetes and Docker with limits #799

Merged
merged 8 commits into from
Feb 1, 2025

Conversation

daniel-sampliner
Copy link
Contributor

@daniel-sampliner daniel-sampliner commented Jan 30, 2025

The value of /sys/fs/cgroup/cpu/cpu.cfs_quota_us is not in milliseconds and cannot be simply divided by 1000 to determine the CPU limit. As per kernel documentation1, the cpu limit can be determined by dividing that value by /sys/fs/cgroup/cpu/cpu.cfs_period_us.

Put an x into the box if that apply:

  • This PR introduces breaking change.
  • This PR fixes a bug.
  • This PR adds new functionality.
  • This PR enhances existing functionality.

Description of your changes

Fixes the max CPU calculation when run inside kubernetes.

How can we test changes

  1. Run pre-commit inside kubernetes pod with CPU limit N.
  2. Without specifying --parallelism-limit, confirm that pre-commit is only spawning N-1 concurrent processes.

Summary by CodeRabbit

  • Bug Fixes
    • Improved CPU core detection mechanism for more accurate resource allocation.
    • Enhanced compatibility with cgroup-based environments.
    • Updated logic for calculating CPU cores based on new variables for quota and period.

Footnotes

  1. https://docs.kernel.org/scheduler/sched-bwc.html

The value of /sys/fs/cgroup/cpu/cpu.cfs_quota_us is not in milliseconds
and cannot be simply divided by 1000 to determine the CPU limit. As per
kernel documentation[^1], the cpu limit can be determined by dividing
that value by /sys/fs/cgroup/cpu/cpu.cfs_period_us.

[^1]: https://docs.kernel.org/scheduler/sched-bwc.html
Copy link

coderabbitai bot commented Jan 30, 2025

Walkthrough

The changes modify the common::get_cpu_num function in the hooks/_common.sh script to enhance the logic for detecting CPU cores. The function now utilizes cpu_quota and cpu_period instead of the previous millicpu variable. The calculation for determining the number of CPU cores has been updated to use the formula cpu_quota / cpu_period, with a minimum return value of 1. Comments have been added to clarify the purpose of the CPU quota calculation in relation to Kubernetes and Docker.

Changes

File Change Summary
hooks/_common.sh - Introduced cpu_quota and cpu_period local variables
- Updated CPU core calculation logic
- Modified return value calculation to use cpu_quota / cpu_period
- Ensured minimum return value of 1
- Added comments for clarification

Sequence Diagram

sequenceDiagram
    participant Script
    participant get_cpu_num Function
    participant cgroup
    
    Script->>get_cpu_num Function: Call function
    get_cpu_num Function->>cgroup: Read cpu_quota
    get_cpu_num Function->>cgroup: Read cpu_period
    get_cpu_num Function->>get_cpu_num Function: Calculate cpu_num = cpu_quota / cpu_period
    alt cpu_num < 1
        get_cpu_num Function-->>Script: Return 1
    else cpu_num >= 1
        get_cpu_num Function-->>Script: Return cpu_num
    end
Loading

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70eefc8 and c6331c0.

📒 Files selected for processing (1)
  • hooks/_common.sh (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • hooks/_common.sh

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
hooks/_common.sh (1)

Line range hint 200-243: Consider adding documentation about cgroup versions.

The implementation looks good, but consider adding comments to explain:

  1. The kernel documentation reference for CPU quota calculation
  2. The differences between cgroup v1 (/sys/fs/cgroup/cpu/) and v2 (/sys/fs/cgroup/) paths
 function common::get_cpu_num {
   local -r parallelism_ci_cpu_cores=$1
 
+  # According to kernel documentation, CPU quota should be calculated as cpu.cfs_quota_us/cpu.cfs_period_us
+  # See: https://www.kernel.org/doc/html/latest/scheduler/sched-bwc.html#cpu-bandwidth-control
   local cpu_quota cpu_period cpu_num
   local millicpu
 
+  # Check for cgroup v1 paths and exclude WSL which has misleading cgroup values
   if [[ -f /sys/fs/cgroup/cpu/cpu.cfs_quota_us &&
     ! -f /proc/sys/fs/binfmt_misc/WSLInterop ]]; then
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dfbde65 and 4ce318b.

📒 Files selected for processing (1)
  • hooks/_common.sh (2 hunks)
🔇 Additional comments (2)
hooks/_common.sh (2)

200-206: LGTM! Clear variable declarations and proper WSL detection.

The code correctly handles edge cases by checking for WSL environment, which could provide misleading cgroup values.


Line range hint 208-243: Correct implementation of CPU quota calculation.

The fix properly implements the CPU core calculation by using cpu.cfs_period_us as per kernel documentation. This resolves the bug where CPU limits were incorrectly calculated in Kubernetes environments.

Key improvements:

  1. Uses cpu_quota/cpu_period instead of the incorrect millicpu/1000
  2. Properly handles edge cases:
    • No CPU limits (cpu_quota = -1)
    • Values less than 1
    • Custom CPU core specifications via parallelism_ci_cpu_cores

@daniel-sampliner daniel-sampliner changed the title fix: parallelism CPU calculation inside k8s Fix: parallelism CPU calculation inside k8s Jan 30, 2025
@daniel-sampliner daniel-sampliner changed the title Fix: parallelism CPU calculation inside k8s fix: parallelism CPU calculation inside k8s Jan 30, 2025
@daniel-sampliner daniel-sampliner changed the title fix: parallelism CPU calculation inside k8s fix: Parallelism CPU calculation inside k8s Jan 30, 2025
hooks/_common.sh Outdated Show resolved Hide resolved
hooks/_common.sh Outdated
Comment on lines 237 to 243
cpu_period=$(< /sys/fs/cgroup/cpu/cpu.cfs_period_us)
cpu_num=$((cpu_quota / cpu_period))
if ((cpu_num < 1)); then
echo 1
else
echo $cpu_num
fi
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@daniel-sampliner Do you think that there's no need for echo $((millicpu / 1000)) as e.g. a fallback if /sys/fs/cgroup/cpu/cpu.cfs_period_us does not exist (in case it may not exist at all)? 🤔

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. I don't believe it's possible for cpu.cfs_period_us to not exist if cpu.cfs_quota_us does exist and is > 0. But I also don't know for certain.

It definitely can't hurt to fall back to something if cpu.cfs_period_us doesn't exist, but I don't think millicpu / 1000 would be the right value. Perhaps like this to default to 1 CPU when cpu.cfs_period_us doesn't exist

Suggested change
cpu_period=$(< /sys/fs/cgroup/cpu/cpu.cfs_period_us)
cpu_num=$((cpu_quota / cpu_period))
if ((cpu_num < 1)); then
echo 1
else
echo $cpu_num
fi
cpu_period=$(< /sys/fs/cgroup/cpu/cpu.cfs_period_us || echo -1)
cpu_num=$((cpu_quota / cpu_period))
[[ $cpu_num -lt 1 ]] && echo 1 || echo $cpu_num

Copy link
Collaborator

@yermulnik yermulnik Jan 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, the above commit suggestion makes sense to me.
@MaxymVlasov WDYT?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
hooks/_common.sh (1)

238-239: Consider adding a comment explaining the CPU calculation formula.

While the implementation is correct, adding a brief comment explaining why we divide cpu_quota by cpu_period would help future maintainers understand the logic.

+    # Calculate CPU cores by dividing quota by period as per cgroup v1 documentation
     cpu_num=$((cpu_quota / cpu_period))
     [[ $cpu_num -lt 1 ]] && echo 1 || echo $cpu_num
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6af478f and b426613.

📒 Files selected for processing (1)
  • hooks/_common.sh (2 hunks)
🔇 Additional comments (3)
hooks/_common.sh (3)

200-207: LGTM! Improved CPU calculation logic.

The changes correctly implement the CPU calculation by using cpu.cfs_quota_us and cpu.cfs_period_us values, which aligns with the kernel documentation for accurate CPU limit calculations in Kubernetes environments.


Line range hint 209-237: Comprehensive error handling for edge cases.

The implementation properly handles various scenarios:

  1. When no CPU limits are set (cpu_quota = -1)
  2. When cpu_period is invalid (< 1)
  3. When running in DinD without limits
  4. When parallelism_ci_cpu_cores is provided but invalid

The warning messages are clear and provide actionable guidance to users.


Line range hint 200-241: Verify the impact on different container runtimes.

The changes handle Kubernetes and Docker environments differently. Let's verify that the CPU calculation works correctly across different container runtimes.

Copy link
Collaborator

@yermulnik yermulnik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. @MaxymVlasov WDYT?

hooks/_common.sh Outdated Show resolved Hide resolved
hooks/_common.sh Outdated
return
fi

if [[ -f /sys/fs/cgroup/cpu.max ]]; then
# Inside Linux (Docker?) container
local millicpu
millicpu=$(cut -d' ' -f1 /sys/fs/cgroup/cpu.max)

if [[ $millicpu == max ]]; then
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regarding thread above about fallbacking to millicpu
In docker we have next picture:
https://docs.docker.com/engine/containers/resource_constraints/#configure-the-default-cfs-scheduler

➜ docker run -ti --cpus="1.5" alpine sh
/ # grep ^ /dev/null /sys/fs/cgroup/cpu*
/sys/fs/cgroup/cpu.idle:0
/sys/fs/cgroup/cpu.max:150000 100000

Where 150000 is cpu-quota and 100000 is cpu-period

150000 / 1000 (millicpu) != 1.5, so, I'll fix it in this PR too

@MaxymVlasov MaxymVlasov requested a review from yermulnik January 31, 2025 22:34
Copy link
Collaborator

@MaxymVlasov MaxymVlasov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great findings

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
hooks/_common.sh (1)

205-211: Accurate Retrieval of CPU Quota and Period Values
The updates correctly read the cpu_quota from /sys/fs/cgroup/cpu/cpu.cfs_quota_us and attempt to retrieve cpu_period from /sys/fs/cgroup/cpu/cpu.cfs_period_us. This ensures that the calculation later uses the proper values from cgroup settings. For consistency and clarity, consider using the same file input redirection style for both values.

-    cpu_period=$(cat /sys/fs/cgroup/cpu/cpu.cfs_period_us 2> /dev/null || echo "$cpu_quota")
+    cpu_period=$(< /sys/fs/cgroup/cpu/cpu.cfs_period_us 2> /dev/null || echo "$cpu_quota")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4a77613 and 70eefc8.

📒 Files selected for processing (1)
  • hooks/_common.sh (3 hunks)
🔇 Additional comments (3)
hooks/_common.sh (3)

Line range hint 213-243: Robust Fallback and Validation for Kubernetes CPU Limits
The conditional block properly checks if either cpu_quota is -1 or cpu_period is less than 1. This branch then either uses the provided parallelism_ci_cpu_cores (after validating it as a positive integer) or falls back gracefully by echoing 1 with an informative warning. This robust handling is well aligned with the PR objective of accurate CPU calculation in Kubernetes environments.


249-259: Proper Handling of cgroup v2 Environments
The new block that handles the /sys/fs/cgroup/cpu.max file correctly addresses scenarios (typically in cgroup v2) where the quota might be expressed differently. The check for a quota value of "max" and the accompanying condition on cpu_period ensure that the function falls back to using nproc when limits are not defined. This implementation cleanly extends support to environments using cgroup v2.


Line range hint 191-259: Overall, CPU Limit Calculation Fix Is Correct and Well-Documented
The modifications in common::get_cpu_num update the CPU calculation to use the formula cpu_quota / cpu_period, which now aligns with the kernel documentation and addresses the previously incorrect division by 1000. The function properly distinguishes between cgroup v1 and v2 while offering robust fallbacks and informative warnings. This fix effectively meets the PR objectives of accurate CPU limit detection in Kubernetes.

@MaxymVlasov MaxymVlasov changed the title fix: Parallelism CPU calculation inside k8s fix: Parallelism CPU calculation inside Kubernetes and Docker with limits Jan 31, 2025
hooks/_common.sh Outdated Show resolved Hide resolved
@MaxymVlasov MaxymVlasov added the bug Something isn't working label Jan 31, 2025
@MaxymVlasov MaxymVlasov merged commit 58a89a1 into antonbabenko:master Feb 1, 2025
43 checks passed
antonbabenko pushed a commit that referenced this pull request Feb 1, 2025
## [1.97.1](v1.97.0...v1.97.1) (2025-02-01)

### Bug Fixes

* Parallelism CPU calculation inside Kubernetes and Docker with limits ([#799](#799)) ([58a89a1](58a89a1))
@antonbabenko
Copy link
Owner

This PR is included in version 1.97.1 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants